<?php
/**
 * 提成管理模型
 */

namespace app\common\model;

use think\model\concern\SoftDelete;

class Commission extends Model
{
    use SoftDelete;
    public $softDelete = true;
    protected $name = 'commission';
    protected $autoWriteTimestamp = true;

    //可搜索字段
    protected $searchField = [];
    protected $whereField = ['staff_id','department_id','commission_time'];

    //是否启用获取器
    public function getStatusTextAttr($value, $data)
    {
        return self::BOOLEAN_TEXT[$data['status']];
    }//提成时间获取器

    public function getCommissionTimeAttr($value)
    {
        return date('Y-m', $value);
    }

//提成时间修改器
    public function setCommissionTimeAttr($value)
    {
        return strtotime($value);
    }


    //附件获取器
    public function getFileAttr($value)
    {
        return json_decode($value, true);
    }

//附件修改器
    public function setFileAttr($value)
    {
        return json_encode($value);
    }

    //关联员工表
    public function staff()
    {
        return $this->belongsTo(Staff::class);
    }

    //关联职位表
    public function department()
    {
        return $this->belongsTo(Department::class);
    }

    public function scopeWheres($query, $param)
    {
        //关键词like搜索
        $keywords = $param['_keywords'] ?? '';
        if (!empty($keywords) && count($this->searchField) > 0) {
            $this->searchField = implode('|', $this->searchField);
            $query->where($this->searchField, 'like', '%' . $keywords . '%');
        }

        //字段条件查询
        if (count($this->whereField) > 0 && count($param) > 0) {
            foreach ($param as $key => $value) {
                if ($value!='' && in_array($key, $this->whereField)) {
                    $query->where($key, $value);
                }
            }
        }
        //排序
        $order = $param['_order'] ?? '';
        $by    = $param['_by'] ?? '';
        $query->order($order ?: '', $by ?: '');
    }
}
